document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded');
    console.log('tableContainer exists:', !!document.getElementById('tableContainer'));
    console.log('All elements with IDs:', document.querySelectorAll('[id]'));
});

let currentDatabase = '';
let currentTable = '';
let currentModal = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 只加载数据库列表
    loadDatabases();
});

// 加载数据库列表
function loadDatabases() {
    console.log('Loading databases...');
    fetch('/api/db/databases')
        .then(response => response.json())
        .then(databases => {
            console.log('Received databases:', databases);
            const databaseList = document.getElementById('databaseList');
            databaseList.innerHTML = '';
            
            databases.forEach(db => {
                const dbItem = document.createElement('div');
                dbItem.className = 'database-item mb-2';
                dbItem.innerHTML = `
                    <div class="d-flex align-items-center">
                        <i class="fa fa-database me-2"></i>
                        <span class="database-name">${db}</span>
                    </div>
                    <div class="tables-container ms-4" style="display: none;"></div>
                `;
                
                // 添加点击事件
                const dbName = dbItem.querySelector('.database-name');
                dbName.addEventListener('click', () => {
                    const tablesContainer = dbItem.querySelector('.tables-container');
                    if (tablesContainer.children.length === 0) {
                        loadTables(db, tablesContainer);
                    }
                    // 切换显示/隐藏
                    tablesContainer.style.display = 
                        tablesContainer.style.display === 'none' ? 'block' : 'none';
                });
                
                databaseList.appendChild(dbItem);
            });
        })
        .catch(error => {
            console.error('Failed to load databases:', error);
            alert('加载数据库列表失败：' + error.message);
        });
}

// 加载表列表
function loadTables(database, container) {
    console.log('Loading tables for database:', database);
    fetch(`/api/db/${database}/tables`)
        .then(response => response.json())
        .then(tables => {
            console.log('Received tables:', tables);
            container.innerHTML = '';
            
            tables.forEach(table => {
                const tableItem = document.createElement('div');
                tableItem.className = 'table-item mb-1';
                tableItem.innerHTML = `
                    <i class="fa fa-table me-2"></i>
                    <span class="table-name">${table}</span>
                `;
                
                // 添加表点击事件
                tableItem.addEventListener('click', () => {
                    console.log('Table clicked:', table);
                    // 更新当前选中的数据库和表
                    currentDatabase = database;
                    currentTable = table;
                    // 加载表数据
                    loadTableData(database, table);
                    // 高亮显示选中的表
                    document.querySelectorAll('.table-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    tableItem.classList.add('active');
                });
                
                container.appendChild(tableItem);
            });
        })
        .catch(error => {
            console.error('Failed to load tables:', error);
            container.innerHTML = `
                <div class="alert alert-danger">
                    加载表列表失败：${error.message}
                </div>
            `;
        });
}

// 执行SQL查询
function executeSQL() {
    const sql = document.getElementById('sqlInput').value;
    
    fetch('/api/db/execute', {
        method: 'POST',
        headers: {
            'Content-Type': 'text/plain',
        },
        body: sql
    })
    .then(response => response.json())
    .then(data => {
        displayQueryResult(data);
    })
    .catch(error => {
        console.error('Error:', error);
        alert('执行失败: ' + error.message);
    });
}

// 显示查询结果
function displayQueryResult(data) {
    const resultDiv = document.getElementById('queryResult');
    resultDiv.innerHTML = '';
    
    if (Array.isArray(data)) {
        // 查询结果
        const table = document.createElement('table');
        table.className = 'table table-bordered table-striped';
        
        // 表头
        if (data.length > 0) {
            const thead = document.createElement('thead');
            const headerRow = document.createElement('tr');
            Object.keys(data[0]).forEach(key => {
                const th = document.createElement('th');
                th.textContent = key;
                headerRow.appendChild(th);
            });
            thead.appendChild(headerRow);
            table.appendChild(thead);
        }
        
        // 数据行
        const tbody = document.createElement('tbody');
        data.forEach(row => {
            const tr = document.createElement('tr');
            Object.values(row).forEach(value => {
                const td = document.createElement('td');
                td.textContent = value;
                tr.appendChild(td);
            });
            tbody.appendChild(tr);
        });
        table.appendChild(tbody);
        
        resultDiv.appendChild(table);
    } else {
        // 更新操作结果
        const alertDiv = document.createElement('div');
        alertDiv.className = 'alert alert-success';
        alertDiv.textContent = `操作成功，影响行数：${data.affectedRows}`;
        resultDiv.appendChild(alertDiv);
    }
}

// 加载表格数据
function loadTableData(database, table, page = 1, size = 10) {
    console.log(`Loading table data: ${database}.${table}, page=${page}, size=${size}`);
    currentDatabase = database;
    currentTable = table;
    
    // 更新当前表信息
    document.getElementById('currentTableTitle').textContent = `${database}.${table}`;
    
    const tableContainer = document.getElementById('tableContainer');
    if (!tableContainer) {
        console.error('Table container not found!');
        return;
    }
    
    // 显示加载状态
    tableContainer.innerHTML = `
        <div class="text-center p-3">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <div class="mt-2">数据加载中...</div>
        </div>
    `;
    
    // 发送请求
    fetch(`/api/db/${database}/${table}/data?page=${page}&size=${size}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取数据失败');
            }
            return response.json();
        })
        .then(result => {
            console.log('Received data:', result);
            displayTableData(result);
        })
        .catch(error => {
            console.error('Error:', error);
            tableContainer.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fa fa-exclamation-circle me-2"></i>
                    加载失败：${error.message}
                </div>
            `;
        });
}

// 显示表格数据
function displayTableData(result) {
    const tableContainer = document.getElementById('tableContainer');
    const { data, total, page, size } = result;
    
    console.log('Displaying data:', {
        dataLength: data?.length,
        total,
        page,
        size
    });
    
    // 添加工具栏
    let html = `
        <div class="mb-3">
            <button class="btn btn-success" onclick="showAddModal()">
                <i class="fa fa-plus"></i> 新增
            </button>
            <span class="ms-3">共 ${total || 0} 条记录</span>
        </div>
    `;
    
    // 检查数据
    if (!data || !Array.isArray(data) || data.length === 0) {
        tableContainer.innerHTML = html + '<div class="alert alert-info">没有数据</div>';
        return;
    }
    
    // 创建表格
    html += `
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover">
                <thead>
                    <tr>
                        <th style="width: 150px">操作</th>
    `;
    
    // 添加表头
    const columns = Object.keys(data[0]).filter(key => key !== 'id'); // 排除id列
    columns.forEach(column => {
        html += `<th>${column}</th>`;
    });
    
    html += '</tr></thead><tbody>';
    
    // 添加数据行
    data.forEach(row => {
        html += '<tr>';
        
        // 添加操作按钮
        html += `
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-primary me-1" onclick="showEditModal('${row.id}')">
                        <i class="fa fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-danger" onclick="deleteRow('${row.id}')">
                        <i class="fa fa-trash"></i> 删除
                    </button>
                </div>
            </td>
        `;
        
        // 添加数据列
        columns.forEach(column => {
            html += `<td>${row[column] !== null ? row[column] : ''}</td>`;
        });
        
        html += '</tr>';
    });
    
    html += '</tbody></table></div>';
    
    // 添加分页
    if (total > size) {
        const totalPages = Math.ceil(total / size);
        html += createPagination(parseInt(page), totalPages);
    }
    
    // 显示表格
    tableContainer.innerHTML = html;
}

// 创建分页组件
function createPagination(currentPage, totalPages) {
    console.log('Creating pagination:', { currentPage, totalPages });
    
    let html = `
        <nav aria-label="Page navigation" class="mt-3">
            <ul class="pagination justify-content-end">
    `;
    
    // 首页
    html += `
        <li class="page-item ${currentPage <= 1 ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" 
               onclick="loadTableData(currentDatabase, currentTable, 1)">
                首页
            </a>
        </li>
    `;
    
    // 上一页
    html += `
        <li class="page-item ${currentPage <= 1 ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" 
               onclick="loadTableData(currentDatabase, currentTable, ${currentPage - 1})">
                上一页
            </a>
        </li>
    `;
    
    // 页码按钮
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    if (endPage - startPage < 4) {
        startPage = Math.max(1, endPage - 4);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="javascript:void(0)" 
                   onclick="loadTableData(currentDatabase, currentTable, ${i})">
                    ${i}
                </a>
            </li>
        `;
    }
    
    // 下一页
    html += `
        <li class="page-item ${currentPage >= totalPages ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" 
               onclick="loadTableData(currentDatabase, currentTable, ${currentPage + 1})">
                下一页
            </a>
        </li>
    `;
    
    // 末页
    html += `
        <li class="page-item ${currentPage >= totalPages ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" 
               onclick="loadTableData(currentDatabase, currentTable, ${totalPages})">
                末页
            </a>
        </li>
    `;
    
    html += '</ul></nav>';
    
    return html;
}

// 点击表名时的处理函数
function onTableClick(database, table) {
    console.log(`Table clicked: ${database}.${table}`);
    currentDatabase = database;
    currentTable = table;
    
    // 更新标题
    const title = document.getElementById('currentTable');
    if (title) {
        title.textContent = `${database}.${table}`;
    }
    
    // 加载数据
    loadTableData(database, table);
}

// 显示分页
function displayPagination(currentPage, totalPages) {
    const container = document.getElementById('paginationContainer');
    if (!container) return;

    container.innerHTML = '';
    
    const nav = document.createElement('nav');
    const ul = document.createElement('ul');
    ul.className = 'pagination justify-content-center';

    // 添加分页项
    // 上一页
    ul.appendChild(createPageItem('上一页', currentPage > 1, currentPage - 1));

    // 页码
    for (let i = 1; i <= totalPages; i++) {
        ul.appendChild(createPageItem(i, true, i, i === currentPage));
    }

    // 下一页
    ul.appendChild(createPageItem('下一页', currentPage < totalPages, currentPage + 1));

    nav.appendChild(ul);
    container.appendChild(nav);
}

// 创建分页项
function createPageItem(text, enabled, page, active = false) {
    const li = document.createElement('li');
    li.className = `page-item ${!enabled ? 'disabled' : ''} ${active ? 'active' : ''}`;
    
    const a = document.createElement('a');
    a.className = 'page-link';
    a.href = '#';
    a.textContent = text;
    
    if (enabled) {
        a.onclick = (e) => {
            e.preventDefault();
            loadTableData(currentDatabase, currentTable, page);
        };
    }
    
    li.appendChild(a);
    return li;
}

// 加载表结构
function loadTableStructure(database, table) {
    fetch(`/api/db/${database}/${table}/structure`)
        .then(response => response.json())
        .then(structure => {
            const structureDiv = document.getElementById('tableStructure');
            structureDiv.innerHTML = '';
            
            const table = document.createElement('table');
            table.className = 'table table-bordered';
            const thead = document.createElement('thead');
            thead.innerHTML = `
                <tr>
                    <th>字段</th>
                    <th>类型</th>
                    <th>可空</th>
                    <th>键</th>
                    <th>默认值</th>
                    <th>额外</th>
                </tr>
            `;
            
            const tbody = document.createElement('tbody');
            structure.forEach(field => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${field.Field}</td>
                    <td>${field.Type}</td>
                    <td>${field.Null}</td>
                    <td>${field.Key}</td>
                    <td>${field.Default || ''}</td>
                    <td>${field.Extra || ''}</td>
                `;
                tbody.appendChild(tr);
            });
            
            table.appendChild(thead).appendChild(tbody);
            structureDiv.appendChild(table);
        })
        .catch(error => {
            console.error('Failed to load table structure:', error);
            alert('加载表结构失败：' + error.message);
        });
}

function showAddModal() {
    console.log('Showing add modal');
    
    // 获取表结构
    fetch(`/api/db/${currentDatabase}/${currentTable}/structure`)
        .then(response => {
            if (!response.ok) throw new Error('获取表结构失败');
            return response.json();
        })
        .then(columns => {
            console.log('Table structure:', columns);
            
            // 生成表单
            const form = document.getElementById('addForm');
            form.innerHTML = '';
            
            columns.forEach(column => {
                // 跳过自增主键
                if (column.isAutoIncrement) return;
                
                const formGroup = document.createElement('div');
                formGroup.className = 'mb-3';
                formGroup.innerHTML = `
                    <label class="form-label">${column.name}</label>
                    <input type="text" class="form-control" name="${column.name}" 
                           ${column.nullable ? '' : 'required'}
                           placeholder="${column.comment || column.name}"/>
                `;
                form.appendChild(formGroup);
            });
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('addModal'));
            modal.show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取表结构失败：' + error.message);
        });
}

// 显示编辑模态框
function showEditModal(id) {
    console.log('Editing row:', id);
    
    // 清空表单
    const form = document.getElementById('dataForm');
    form.innerHTML = '';
    
    // 获取数据
    fetch(`/api/db/${currentDatabase}/${currentTable}/row/${id}`)
        .then(response => {
            if (!response.ok) throw new Error('获取数据失败');
            return response.json();
        })
        .then(data => {
            console.log('Row data:', data);
            
            // 保存ID到表单
            form.setAttribute('data-id', id);
            
            // 创建表单字段
            Object.entries(data).forEach(([key, value]) => {
                if (key.toLowerCase() !== 'id') {
                    const formGroup = document.createElement('div');
                    formGroup.className = 'mb-3';
                    formGroup.innerHTML = `
                        <label class="form-label">${key}</label>
                        <input type="text" class="form-control" name="${key}" value="${value || ''}" />
                    `;
                    form.appendChild(formGroup);
                }
            });
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('dataModal'));
            modal.show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取数据失败：' + error.message);
        });
}

// 保存数据
function saveData() {
    console.log('Saving data...');
    
    const form = document.getElementById('dataForm');
    const id = form.getAttribute('data-id');
    
    if (!id) {
        console.error('No ID found');
        return;
    }
    
    // 显示保存中状态
    const saveButton = document.querySelector('#dataModal .btn-primary');
    const originalText = saveButton.innerHTML;
    saveButton.disabled = true;
    saveButton.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 保存中...';
    
    // 收集表单数据
    const formData = {};
    form.querySelectorAll('input').forEach(input => {
        formData[input.name] = input.value;
    });
    
    console.log('Form data:', formData);
    
    // 发送更新请求
    fetch(`/api/db/${currentDatabase}/${currentTable}/update/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(error => {
                throw new Error(error.message || '保存失败');
            });
        }
        return response.json();
    })
    .then(result => {
        console.log('Save successful:', result);
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('dataModal'));
        modal.hide();
        
        // 刷新表格数据
        loadTableData(currentDatabase, currentTable);
        
        // 显示成功消息
        alert('保存成功！');
    })
    .catch(error => {
        console.error('Save error:', error);
        alert('保存失败：' + error.message);
    })
    .finally(() => {
        // 恢复按钮状态
        saveButton.disabled = false;
        saveButton.innerHTML = originalText;
    });
}

// 删除行的函数
function deleteRow(id) {
    if (!confirm('确定要删除这条记录吗？')) {
        return;
    }
    
    fetch(`/api/db/${currentDatabase}/${currentTable}/delete/${id}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('删除失败');
        }
        // 刷新表格数据
        loadTableData(currentDatabase, currentTable);
        alert('删除成功！');
    })
    .catch(error => {
        console.error('Delete error:', error);
        alert('删除失败：' + error.message);
    });
}

function exportExcel() {
    window.location.href = `/api/db/${currentDatabase}/${currentTable}/export/excel`;
}

function exportSql() {
    window.location.href = `/api/db/${currentDatabase}/${currentTable}/export/sql`;
}

// 保存新数据
function saveNewData() {
    console.log('Saving new data...');
    
    // 显示保存中状态
    const saveButton = document.querySelector('#addModal .btn-primary');
    const originalText = saveButton.innerHTML;
    saveButton.disabled = true;
    saveButton.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 保存中...';
    
    // 收集表单数据
    const form = document.getElementById('addForm');
    const formData = {};
    form.querySelectorAll('input').forEach(input => {
        formData[input.name] = input.value;
    });
    
    console.log('Form data:', formData);
    
    // 发送新增请求
    fetch(`/api/db/${currentDatabase}/${currentTable}/insert`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(error => {
                throw new Error(error.message || '保存失败');
            });
        }
        return response.json();
    })
    .then(result => {
        console.log('Save successful:', result);
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('addModal'));
        modal.hide();
        
        // 刷新表格数据
        loadTableData(currentDatabase, currentTable);
        
        // 显示成功消息
        alert('新增成功！');
    })
    .catch(error => {
        console.error('Save error:', error);
        alert('保存失败：' + error.message);
    })
    .finally(() => {
        // 恢复按钮状态
        saveButton.disabled = false;
        saveButton.innerHTML = originalText;
    });
}

// 执行 SQL
function executeSql() {
    const sql = document.getElementById('sqlInput').value.trim();
    if (!sql) {
        alert('请输入 SQL 语句');
        return;
    }

    // 显示加载状态
    const resultDiv = document.getElementById('sqlResult');
    resultDiv.innerHTML = `
        <div class="text-center p-3">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">执行中...</span>
            </div>
            <div class="mt-2">SQL 执行中...</div>
        </div>
    `;

    // 判断是查询还是更新操作
    const isSelect = sql.toLowerCase().trim().startsWith('select');
    const url = `/api/db/execute${isSelect ? 'Query' : 'Update'}`;

    // 发送请求
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ sql: sql })
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(error => {
                throw new Error(error.message || '执行失败');
            });
        }
        return response.json();
    })
    .then(result => {
        console.log('SQL execution result:', result);
        
        if (isSelect) {
            // 显示查询结果
            displayQueryResult(result);
        } else {
            // 显示更新结果
            resultDiv.innerHTML = `
                <div class="alert alert-success">
                    <i class="fa fa-check-circle"></i>
                    执行成功！影响行数：${result.affectedRows}
                </div>
            `;
        }
    })
    .catch(error => {
        console.error('SQL execution error:', error);
        resultDiv.innerHTML = `
            <div class="alert alert-danger">
                <i class="fa fa-exclamation-circle"></i>
                执行失败：${error.message}
            </div>
        `;
    });
}

// 显示查询结果
function displayQueryResult(data) {
    const resultDiv = document.getElementById('sqlResult');
    
    if (!Array.isArray(data) || data.length === 0) {
        resultDiv.innerHTML = '<div class="alert alert-info">查询结果为空</div>';
        return;
    }

    // 创建表格
    let html = `
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover">
                <thead>
                    <tr>
    `;
    
    // 添加表头
    const columns = Object.keys(data[0]);
    columns.forEach(column => {
        html += `<th>${column}</th>`;
    });
    
    html += '</tr></thead><tbody>';
    
    // 添加数据行
    data.forEach(row => {
        html += '<tr>';
        columns.forEach(column => {
            html += `<td>${row[column] !== null ? row[column] : ''}</td>`;
        });
        html += '</tr>';
    });
    
    html += `
                </tbody>
            </table>
        </div>
        <div class="mt-2">
            共 ${data.length} 条记录
        </div>
    `;
    
    resultDiv.innerHTML = html;
}

// 清空 SQL
function clearSql() {
    document.getElementById('sqlInput').value = '';
    document.getElementById('sqlResult').innerHTML = '';
} 